package com.example.doer.reading.AppActivities;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.activity.AbActivity;
import com.ab.http.AbHttpUtil;
import com.ab.http.AbStringHttpResponseListener;
import com.ab.image.AbImageLoader;
import com.ab.view.titlebar.AbTitleBar;
import com.example.doer.reading.AppDataModel.CircleImageView;
import com.example.doer.reading.AppDataModel.Theme;
import com.example.doer.reading.AppDataModel.Topic;
import com.example.doer.reading.AppDataModel.TopicReply;
import com.example.doer.reading.R;
import com.example.doer.reading.global.MyApplication;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.ab.util.AbToastUtil.showToast;

/**
 * Created by 严旭江 on 2017/7/20.
 */

public class ThemeActivity extends AbActivity implements View.OnClickListener {
    static String themeName = "";//传递过来的themeName
    AbTitleBar abTitleBar;
    Theme theme;//产生得到的theme对象
    CircleImageView themeLogo;//话题logo
    TextView themeCollect;//收藏关注btn
    TextView themeDesc;//话题的描述
    ListView listView;//话题所有的列举Reply的listView
    ThemeAdapter themeAdapter = null;//适配器
    List<Topic>topicList = new ArrayList<Topic>();//该Theme的所有Topic
    int themeFocusNum;
    String themeDescribe;
    static boolean isFocus;//静态变量  用户是否关注过？
    Button returnBtn;
    TextView themeName_tv;
    @Override
    public void onCreate(Bundle savedInstacetype){
        super.onCreate(savedInstacetype);
        setAbContentView(R.layout.activity_theme);
        //abTitleBar = this.getTitleBar();//获取传递得到的themeName
        Intent intent = this.getIntent();
        Bundle bundle = intent.getExtras();
        themeName = bundle.getString("themeName");
        themeCollect = (TextView)findViewById(R.id.themeCollectBtn);
        listView = (ListView)findViewById(R.id.themeListView);
        themeLogo = (CircleImageView)findViewById(R.id.themeLogo);
        returnBtn = (Button)findViewById(R.id.ThemeActivity_btnReturn);
        themeDesc = (TextView)findViewById(R.id.themeDesc);
        themeName_tv = (TextView)findViewById(R.id.ThemeName_tv);
        themeName_tv.setText(themeName);
        /**
         * 用户ID全局获取
         */
        String UserID = MyApplication.user.getUserID();
        String url="http://192.168.191.1/Reading/TopicServlet?Action=down&userID="+UserID+"&topicName="+themeName;
        AbHttpUtil abHttpUtil= AbHttpUtil.getInstance(this);
        abHttpUtil.get(url, new AbStringHttpResponseListener() {
            @Override
            public void onSuccess(int i, String s) {//s为传递下来的jsonstring
                try {
                   JSONObject jo = new JSONObject(s).getJSONObject("QuestionList");
                    //themeName = = jo.getString("TopicName");
                    themeFocusNum = jo.getInt("TopicFocusNum");
                    themeDescribe = jo.getString("TopicDescription");
                    themeDesc.setText(themeDescribe);
                    isFocus = jo.getBoolean("isFocus");
                    JSONArray jsonArray= jo.getJSONArray("questionInit");
                    //创建Topic的对象集合
                    Topic addTopic;
                    TopicReply addTopicReply;
                    for (int j=0;j<jsonArray.length();j++){
                        JSONObject jsonObject = (JSONObject)jsonArray.get(j);//Theme名字  一级
                        String themeName = jsonObject.getString("QuestionFromTopicName");
                        String themeLogoPath = jsonObject.getString("topic_logo");
                        //问题名字   二级
                        String topicName = jsonObject.getString("QuestTitle");
                        String topicID = jsonObject.getString("QuestID");
                        String topicDesc = jsonObject.getString("QuestDescription");
                        String topicFavourCount = jsonObject.getString("QuestionFocusCount");
                        String topicCollectCount = jsonObject.getString("QuestionAnswerCount");
                        if (!jsonObject.isNull("answer")) {
                            JSONObject thirdObj = (JSONObject) jsonObject.get("answer");
                            String thirdObjID = thirdObj.getString("AnswerID");
                            String thirdObjFromTopicID = thirdObj.getString("AnswerFromQuestID");
                            String thirdObjContent = thirdObj.getString("AnswerContent");
                            //额外新增 回复的用户名
                            String thirdObjUserName = thirdObj.getString("AnswerFromUserName");
                            String thirdObjUserID = thirdObj.getString("AnswerFromUserID");
                            String thirdObjFavourCount = thirdObj.getString("ThumbUpCount");
                            String thirdObjReplyCount = thirdObj.getString("ReplyCount");
                            String thirdObjCollectCount = thirdObj.getString("UserCollectCount");
                            boolean thirdObjIsThumbUp = thirdObj.getBoolean("IsThumbUp");
                            boolean thirdObjIsCollect = thirdObj.getBoolean("IsCollect");
                            addTopicReply = new TopicReply(thirdObjID,thirdObjFromTopicID,thirdObjUserID,thirdObjUserName,thirdObjContent,Integer.valueOf(thirdObjFavourCount),Integer.valueOf(thirdObjCollectCount),Integer.valueOf(thirdObjReplyCount),thirdObjIsThumbUp,thirdObjIsCollect);
                            addTopic = new Topic(topicID,themeName,themeLogoPath,topicName,topicDesc,Integer.valueOf(topicCollectCount),Integer.valueOf(topicFavourCount),addTopicReply);
                            topicList.add(addTopic);
                        }
                        else {
                            //说明问题没有回答
                            addTopic = new Topic(topicID,themeName,themeLogoPath,topicName,topicDesc,Integer.valueOf(topicCollectCount),Integer.valueOf(topicFavourCount));
                            topicList.add(addTopic);
                        }
                    }//end for
                    if(jsonArray.length()!=0){
                        themeAdapter = new ThemeAdapter(topicList, R.layout.topic_listview);
                        listView.setAdapter(themeAdapter);
                    }else{}//listView.setEmptyView(View);}
                    /**
                     * 设置LOGO与Desc
                     */
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onStart() {

            }
            @Override
            public void onFinish() {
            }
            @Override
            public void onFailure(int i, String s, Throwable throwable) {
                showToast(ThemeActivity.this,"Theme请求失败");
            }
        });
        Drawable dra = null;
        if(!isFocus)
            dra = getResources().getDrawable(R.drawable.icon_collect_initial);
        else dra = getResources().getDrawable(R.drawable.icon_collect_selected);
        dra.setBounds(0, 0, dra.getMinimumWidth(), dra.getMinimumHeight());
        themeCollect.setCompoundDrawables(dra,null,null,null);
        themeCollect.setText(themeFocusNum+"关注");

        themeCollect.setOnClickListener(this);
        returnBtn.setOnClickListener(this);
    }//end onCreate method

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ThemeActivity_btnReturn://返回按钮
                ThemeActivity.this.finish();
                break;
            case R.id.themeCollectBtn:{//关注收藏按钮
                Drawable newDra = null;
                if(isFocus){//已经关注过   点击后 撤销关注
                    newDra = getResources().getDrawable(R.drawable.icon_collect_initial);
                    newDra.setBounds(0, 0, newDra.getMinimumWidth(), newDra.getMinimumHeight());
                    themeCollect.setCompoundDrawables(newDra,null,null,null);
                    themeFocusNum -=1;
                    themeCollect.setText(themeFocusNum+"关注");
                    getHTTPResponse(false);
                    isFocus = !isFocus;
                }else{
                    newDra = getResources().getDrawable(R.drawable.icon_collect_selected);
                    newDra.setBounds(0, 0, newDra.getMinimumWidth(), newDra.getMinimumHeight());
                    themeCollect.setCompoundDrawables(newDra,null,null,null);
                    themeFocusNum+=1;
                    themeCollect.setText((themeFocusNum)+"关注");
                    getHTTPResponse(true);
                    isFocus = !isFocus;
                }
            }
        }
    }

    private void getHTTPResponse(boolean isCollect){
        AbHttpUtil abHttpUtil;
        abHttpUtil = AbHttpUtil.getInstance(ThemeActivity.this);
        if(isCollect){//->未关注变为关注
            String url = "http://192.168.191.1/Reading/MessageServlet?Action=focusTopic&userID="+MyApplication.user.getUserID()+"&userName="+MyApplication.user.getUserName()+"&value="+themeName;
            abHttpUtil.get(url, new AbStringHttpResponseListener() {
                @Override
                public void onSuccess(int i, String s) {
                    Toast.makeText(ThemeActivity.this,"关注话题成功",Toast.LENGTH_SHORT);

                }

                @Override
                public void onStart() {

                }

                @Override
                public void onFinish() {

                }

                @Override
                public void onFailure(int i, String s, Throwable throwable) {
                    showToast(ThemeActivity.this,"关注失败");
                }
            });
        }
        else{//关注变为未关注  即取消关注
            String url = "http://192.168.191.1/Reading/MessageServlet?Action=cancelFocus&userID="+MyApplication.user.getUserID()+"&userName="+MyApplication.user.getUserName()+"&value="+themeName;
            abHttpUtil.get(url, new AbStringHttpResponseListener() {
                @Override
                public void onSuccess(int i, String s) {
                    Toast.makeText(ThemeActivity.this,"你已取消关注",Toast.LENGTH_SHORT);
                }
                @Override
                public void onStart() {
                }

                @Override
                public void onFinish() {

                }

                @Override
                public void onFailure(int i, String s, Throwable throwable) {
                    showToast(ThemeActivity.this,"取消关注失败");
                }
            });

        }
    }

    class ThemeAdapter extends BaseAdapter{
        List<Topic> topicList;
        int count = 10;//初始化显示10条
        int resID;//布局ID
        Topic topic;
        AbImageLoader mAbImageLoader;
        LinearLayout layout = null;//水平布局
        public ThemeAdapter(List<Topic>theTopicList, int theResID){
            topicList = theTopicList;
            resID = theResID;
            mAbImageLoader=new AbImageLoader(ThemeActivity.this);
        }
        @Override
        public Topic getItem(int position) {
            return topicList.get(position);
        }
        @Override
        public long getItemId(int positon){
            return positon;
        }
        @Override
        public int getCount() {
            return topicList.size();
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent){
            convertView = LayoutInflater.from(ThemeActivity.this).inflate(resID,null);
            topic = (Topic)getItem(position);
            /**
             * 几个主要控件的引用
             */
            layout = (LinearLayout)convertView.findViewById(R.id.topicLinearLay);
//            CircleImageView topicImg = (CircleImageView)findViewById(R.id.topicImageView);
            TextView topicName = (TextView)convertView.findViewById(R.id.topicName);

            layout.setVisibility(View.GONE);
            TextView replyContent = (TextView)convertView.findViewById(R.id.topicContent);
            TextView replyFavourCount = (TextView)convertView.findViewById(R.id.topicAgreeNumber);
            TextView replyCommentCount = (TextView)convertView.findViewById(R.id.topicCommentNumber);

            if(topic.getaTopicReply()!=null) {
                replyContent.setText(topic.getaTopicReply().getReplyContent());
                replyFavourCount.setText("点赞数:"+topic.getaTopicReply().getFavoCount());
                replyCommentCount.setText("评论数："+topic.getReplyCount());
            }
            else {
                replyContent.setVisibility(View.GONE);
                replyFavourCount.setVisibility(View.GONE);
                replyCommentCount.setVisibility(View.GONE);
            }


            topicName.setText(topic.getTopicName());

            //mAbImageLoader.display(userImg,"",100,100);
            //mAbImageLoader.display(imageView,Constant.BASEURL+"Action=download&Category=BookCover&ImageName="+book.getBookNo(),100,100);
            /**
             * 点击问题名字跳转事件
             */
            topicName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ThemeActivity.this,TopicWithReplyActivity.class);
                    intent.putExtra("topicObjWithReply",topic);
                    startActivity(intent);
                }
            });
            /**
             * 点击问题回答内容跳转事件
             */
            replyContent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ThemeActivity.this,TopicActivity.class);
                    intent.putExtra("topicReplyObj",topic);
                    startActivity(intent);
                }
            });
            return convertView;
        }
    }//end adapter class
}//end Activity class
